package com.xxl.vueadmin.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @version 1.0
 * @Author: 许啸林 jwt 工具类
 * @Date: 2021/7/30 13:48
 */
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {
    private long expire;
    private String secret;
    private String Header;

    /**
     * 生成jwt
     * @param userName
     * @return
     */
    public  String generateToken(String userName) {
        Date newDate = new Date();
        Date expireDate = new Date(newDate.getTime() + expire * 10000);
        return Jwts.builder().setHeaderParam("typ", "JWT")
                             .setSubject(userName)
                             .setIssuedAt(newDate)
                             .setExpiration(expireDate)
                             .signWith(SignatureAlgorithm.HS512, secret)
                             .compact();
    }

    /**
     *  获取载荷
     * @param token
     * @return
     */
    public  Claims getClaims(String token) {
        try {
            return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        }catch (Exception e) {
            return  null;
        }

    }
    public  boolean checkExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
